from flask import Blueprint, render_template, jsonify, request
from flask_login import login_required, current_user
from app import db
from app.models.order import Order, OrderItem
from app.models.blind_box import BlindBox
from app.models.user_behavior import UserBehavior
import pandas as pd
from datetime import datetime, timedelta
from app.utils.tracking import track_user_behavior
from app.analytics.data_loader import DataLoader
from app.analytics.time_series import TimeSeriesModel
from app.analytics.seasonality import SeasonalityAnalyzer
from app.analytics.price_elasticity import PriceElasticityAnalyzer
from app.analytics.visualization import Visualizer

analytics = Blueprint('analytics', __name__, url_prefix='/analytics')

@analytics.route('/dashboard')
@login_required
def dashboard():
    """数据分析仪表板"""
    return render_template('analytics/dashboard.html')

@analytics.route('/user_behavior')
@login_required
def user_behavior_dashboard():
    """用户行为分析仪表板"""
    return render_template('analytics/user_behavior.html')

@analytics.route('/api/sales_summary')
@login_required
def api_sales_summary():
    """销售统计数据API"""
    # 获取最近30天销售数据
    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)
    
    daily_sales = db.session.query(
        db.func.date(Order.create_time).label('date'),
        db.func.sum(Order.total_amount).label('amount'),
        db.func.count(Order.order_id).label('count')
    ).filter(
        Order.create_time.between(start_date, end_date),
        Order.status.in_([2, 3])  # 已支付和已完成的订单
    ).group_by(
        db.func.date(Order.create_time)
    ).all()
    
    # 转换为JSON友好格式
    result = [{
        'date': str(row.date),
        'amount': float(row.amount),
        'count': row.count
    } for row in daily_sales]
    
    return jsonify(result)

@analytics.route('/api/popular_boxes')
@login_required
def api_popular_boxes():
    """热门盲盒API"""
    # 获取最近30天销量最高的盲盒
    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)
    
    # 注意：order表可能没有直接关联到box_id，需要通过OrderItem表
    # 根据实际数据库结构修正查询
    popular_boxes = db.session.query(
        BlindBox.box_id,
        BlindBox.name,
        BlindBox.image_url,
        db.func.sum(OrderItem.price * OrderItem.quantity).label('revenue'),
        db.func.count(OrderItem.detail_id).label('order_count')
    ).join(
        OrderItem, BlindBox.box_id == OrderItem.box_id
    ).join(
        Order, OrderItem.order_id == Order.order_id
    ).filter(
        Order.create_time.between(start_date, end_date),
        Order.status.in_([2, 3])  # 已支付和已完成的订单
    ).group_by(
        BlindBox.box_id, BlindBox.name, BlindBox.image_url
    ).order_by(
        db.func.count(OrderItem.detail_id).desc()
    ).limit(10).all()
    
    # 转换为JSON友好格式
    result = [{
        'box_id': row.box_id,
        'name': row.name,
        'image_url': row.image_url,
        'revenue': float(row.revenue) if row.revenue else 0,
        'order_count': row.order_count
    } for row in popular_boxes]
    
    return jsonify(result)

@analytics.route('/api/user_behavior')
@login_required
def api_user_behavior():
    """用户行为统计API"""
    # 获取最近7天用户行为数据
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)
    
    behaviors = db.session.query(
        UserBehavior.action_type,
        db.func.count(UserBehavior.behavior_id).label('count')
    ).filter(
        UserBehavior.create_time.between(start_date, end_date),
        ~UserBehavior.action_type.in_(['view'])  # 只排除一般的view
    ).group_by(
        UserBehavior.action_type
    ).all()
    
    result = [{
        'behavior_type': row.action_type,
        'count': row.count
    } for row in behaviors]
    
    return jsonify(result)

@analytics.route('/api/behavior_trends')
@login_required
def api_behavior_trends():
    """获取用户行为趋势数据"""
    days = int(request.args.get('days', 14))  # 默认14天
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)
    
    # 获取每日各类行为次数
    daily_behaviors = db.session.query(
        db.func.date(UserBehavior.create_time).label('date'),
        UserBehavior.action_type,
        db.func.count(UserBehavior.behavior_id).label('count')
    ).filter(
        UserBehavior.create_time.between(start_date, end_date),
        ~UserBehavior.action_type.in_(['view'])  # 只排除一般的view
    ).group_by(
        db.func.date(UserBehavior.create_time),
        UserBehavior.action_type
    ).all()
    
    # 转换为适合图表的格式
    dates = sorted(list(set(str(row.date) for row in daily_behaviors)))
    behavior_types = sorted(list(set(row.action_type for row in daily_behaviors)))
    
    # 创建结果字典
    result = {
        'dates': dates,
        'behavior_types': behavior_types,
        'series': []
    }
    
    # 为每种行为类型创建系列数据
    for behavior_type in behavior_types:
        data = []
        for date in dates:
            # 查找当天该行为的次数
            count = next((row.count for row in daily_behaviors 
                         if str(row.date) == date and row.action_type == behavior_type), 0)
            data.append(count)
            
        result['series'].append({
            'name': behavior_type,
            'data': data,
            'type': 'line'
        })
    
    return jsonify(result)

@analytics.route('/api/funnel_analysis')
@login_required
def api_funnel_analysis():
    """页面转化漏斗分析"""
    days = int(request.args.get('days', 30))  # 默认30天
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)
    
    # 计算各步骤的用户数
    visitors = db.session.query(db.func.count(db.func.distinct(UserBehavior.user_id))).filter(
        UserBehavior.create_time.between(start_date, end_date),
        ~UserBehavior.action_type.in_(['view'])  # 只排除一般的view
    ).scalar()
    
    # 查看商品用户数
    product_viewers = db.session.query(db.func.count(db.func.distinct(UserBehavior.user_id))).filter(
        UserBehavior.create_time.between(start_date, end_date),
        UserBehavior.action_type == 'view_box'
    ).scalar()
    
    # 加入购物车用户数
    cart_adders = db.session.query(db.func.count(db.func.distinct(UserBehavior.user_id))).filter(
        UserBehavior.create_time.between(start_date, end_date),
        UserBehavior.action_type == 'add_to_cart'
    ).scalar()
    
    # 从订单表获取下单用户数
    purchasers = db.session.query(db.func.count(db.func.distinct(Order.user_id))).filter(
        Order.create_time.between(start_date, end_date),
        Order.status.in_([1, 2, 3])  # 包括待付款、已支付和已完成的订单
    ).scalar()
    
    result = {
        'stages': ['访问', '查看商品', '加入购物车', '下单'],
        'values': [visitors, product_viewers, cart_adders, purchasers],
        'conversion_rates': [
            100,  # 访问转化率始终为100%
            round(product_viewers/visitors*100, 2) if visitors else 0,  # 浏览商品转化率
            round(cart_adders/product_viewers*100, 2) if product_viewers else 0,  # 加购转化率
            round(purchasers/cart_adders*100, 2) if cart_adders else 0  # 下单转化率
        ]
    }
    
    return jsonify(result)

@analytics.route('/api/popular_pages')
@login_required
def api_popular_pages():
    """热门页面分析"""
    days = int(request.args.get('days', 7))  # 默认7天
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)
    
    # 获取访问次数最多的页面
    popular_pages = db.session.query(
        UserBehavior.url,
        db.func.count(UserBehavior.behavior_id).label('visit_count'),
        db.func.count(db.func.distinct(UserBehavior.user_id)).label('unique_users')
    ).filter(
        UserBehavior.create_time.between(start_date, end_date),
        UserBehavior.action_type.in_(['page_view', 'view_box', 'view_market', 'view_order'])  # 包含page_view和特定view
    ).group_by(
        UserBehavior.url
    ).order_by(
        db.func.count(UserBehavior.behavior_id).desc()
    ).limit(10).all()
    
    result = [{
        'url': row.url,
        'visit_count': row.visit_count,
        'unique_users': row.unique_users,
        'avg_visits_per_user': round(row.visit_count / row.unique_users, 2) if row.unique_users else 0
    } for row in popular_pages]
    
    return jsonify(result)

@analytics.route('/api/search_keywords')
@login_required
def api_search_keywords():
    """用户搜索词分析"""
    days = int(request.args.get('days', 30))  # 默认30天
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)
    
    # 获取最常见的搜索词 - 修改过滤条件
    search_keywords = db.session.query(
        UserBehavior.query,
        db.func.count(UserBehavior.behavior_id).label('search_count')
    ).filter(
        UserBehavior.create_time.between(start_date, end_date),
        UserBehavior.url.like('%search%'),  # 改为查找URL中包含search的
        UserBehavior.query.isnot(None),  # 不为空的搜索词
        UserBehavior.query != ''  # 不为空字符串
    ).group_by(
        UserBehavior.query
    ).order_by(
        db.func.count(UserBehavior.behavior_id).desc()
    ).limit(20).all()
    
    result = [{
        'keyword': row.query,
        'count': row.search_count
    } for row in search_keywords]
    
    return jsonify(result)

@analytics.route('/advanced')
@login_required
def advanced():
    """高级分析页面"""
    return render_template('analytics/advanced.html')

@analytics.route('/api/category_analysis')
@login_required
def api_category_analysis():
    """类别分析数据API"""
    # 导入需要的模型
    from app.models.order import Order, OrderItem
    
    # 按类别统计销售情况
    category_data = db.session.query(
        BlindBox.category,
        db.func.count(OrderItem.detail_id).label('order_count'),
        db.func.sum(OrderItem.price * OrderItem.quantity).label('total_sales')
    ).join(
        OrderItem, BlindBox.box_id == OrderItem.box_id
    ).join(
        Order, OrderItem.order_id == Order.order_id
    ).filter(
        Order.status.in_([2, 3])  # 已支付和已完成的订单
    ).group_by(
        BlindBox.category
    ).all()
    
    # 转换为JSON友好格式
    result = [{
        'category': row.category or '未分类',
        'order_count': row.order_count,
        'total_sales': float(row.total_sales) if row.total_sales else 0
    } for row in category_data]
    
    return jsonify(result)

@analytics.route('/api/customer_retention')
@login_required
def api_customer_retention():
    """客户留存分析API"""
    # 计算客户复购率
    # 查询至少下单两次的用户数
    repeat_users = db.session.query(
        Order.user_id,
        db.func.count(Order.order_id).label('order_count')
    ).filter(
        Order.status.in_([2, 3])  # 已支付和已完成的订单
    ).group_by(
        Order.user_id
    ).having(
        db.func.count(Order.order_id) >= 2
    ).count()
    
    # 查询总下单用户数
    total_users = db.session.query(
        db.func.count(db.func.distinct(Order.user_id))
    ).filter(
        Order.status.in_([2, 3])  # 已支付和已完成的订单
    ).scalar()
    
    # 计算复购率
    retention_rate = (repeat_users / total_users) * 100 if total_users else 0
    
    # 最近30天的新用户数
    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)
    
    new_users = db.session.query(
        db.func.count(db.func.distinct(Order.user_id))
    ).filter(
        Order.create_time.between(start_date, end_date),
        Order.status.in_([2, 3])  # 已支付和已完成的订单
    ).scalar()
    
    result = {
        'repeat_users': repeat_users,
        'total_users': total_users,
        'retention_rate': retention_rate,
        'new_users_30d': new_users
    }
    
    return jsonify(result)

@analytics.route('/api/conversion_funnel')
@login_required
def api_conversion_funnel():
    """转化漏斗API"""
    # 获取最近30天行为数据
    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)
    
    # 查询各类行为数量
    # 页面浏览数量
    page_view_count = db.session.query(UserBehavior).filter(
        UserBehavior.action_type == 'page_view',
        UserBehavior.create_time.between(start_date, end_date)
    ).count()
    
    # 查看商品数量
    view_box_count = db.session.query(UserBehavior).filter(
        UserBehavior.action_type == 'view_box',
        UserBehavior.create_time.between(start_date, end_date)
    ).count()
    
    add_cart_count = db.session.query(UserBehavior).filter(
        UserBehavior.action_type == 'add_to_cart',
        UserBehavior.create_time.between(start_date, end_date)
    ).count()
    
    purchase_count = db.session.query(UserBehavior).filter(
        UserBehavior.action_type == 'form_submit',
        UserBehavior.create_time.between(start_date, end_date)
    ).count()
    
    # 计算转化率
    page_to_view = (view_box_count / page_view_count) * 100 if page_view_count else 0
    view_to_cart = (add_cart_count / view_box_count) * 100 if view_box_count else 0
    cart_to_purchase = (purchase_count / add_cart_count) * 100 if add_cart_count else 0
    
    result = {
        'page_view': page_view_count,
        'view': view_box_count,
        'add_cart': add_cart_count,
        'purchase': purchase_count,
        'page_to_view_rate': page_to_view,
        'view_to_cart_rate': view_to_cart,
        'cart_to_purchase_rate': cart_to_purchase
    }
    
    return jsonify(result)

@analytics.route('/sales_prediction')
@login_required
def sales_prediction():
    """销售预测页面"""
    # 获取URL参数，用于决定是否自动运行分析
    analysis_type = request.args.get('type', 'forecast')
    auto_run = request.args.get('auto', 'false')
    
    # 构建模板上下文
    context = {
        'auto_run': auto_run,
        'analysis_type': analysis_type
    }
    
    return render_template('analytics/sales_prediction.html', **context)

@analytics.route('/api/sales_forecast')
@login_required
def api_sales_forecast():
    """销售预测API"""
    try:
        # 获取请求参数
        category = request.args.get('category')
        box_id = request.args.get('box_id')
        days = int(request.args.get('days', 365))
        forecast_days = int(request.args.get('forecast_days', 30))
        model_type = request.args.get('model_type', 'prophet')  # 'arima' 或 'prophet'
        
        print(f"销售预测请求参数: category={category}, box_id={box_id}, days={days}, forecast_days={forecast_days}, model_type={model_type}")
        
        # 加载数据
        loader = DataLoader()
        df = loader.get_sales_data(days=days, category=category, box_id=box_id)
        
        print(f"加载的数据点数量: {len(df)}")
        
        # 数据不足
        if len(df) < 30:
            print("历史数据不足，无法进行预测分析")
            return jsonify({
                'success': False,
                'message': '历史数据不足，无法进行预测分析'
            })
        
        # 如果指定了盲盒ID，使用盲盒名称作为标题
        title_prefix = ""
        if box_id:
            # 获取第一行的盲盒名称
            if 'name' in df.columns and not df.empty:
                box_name = df.iloc[0]['name']
                title_prefix = f"{box_name} - "
        
        # 按日期聚合
        agg_df = df.groupby('date')['sales_quantity'].sum().reset_index()
        agg_df = pd.DataFrame({
            'date': agg_df['date'],
            'sales_quantity': agg_df['sales_quantity']
        })
        
        print(f"聚合后的数据点数量: {len(agg_df)}")
        
        # 准备时间序列数据
        ts_data = loader.prepare_time_series_data(agg_df)
        
        # 创建时间序列模型
        ts_model = TimeSeriesModel(ts_data)
        
        # 进行预测
        if model_type == 'arima':
            # ARIMA模型
            try:
                print("使用ARIMA模型预测")
                ts_model.fit_arima(order=(1, 1, 1))
                forecast = ts_model.predict_arima(steps=forecast_days)
            except Exception as e:
                print(f"ARIMA预测失败: {str(e)}")
                return jsonify({
                    'success': False,
                    'message': f'ARIMA预测失败: {str(e)}'
                })
        else:
            # Prophet模型
            try:
                print("使用Prophet模型预测")
                ts_model.fit_prophet()
                forecast_raw = ts_model.predict_prophet(periods=forecast_days)
                
                # 转换Prophet输出格式
                forecast = pd.DataFrame({
                    'date': forecast_raw['ds'].tail(forecast_days),
                    'sales_quantity_pred': forecast_raw['yhat'].tail(forecast_days).values
                }).set_index('date')
                
                # 生成图表，转为base64
                chart_title = f"{title_prefix}盲盒销售预测"
                fig = ts_model.plot_prophet_forecast(title=chart_title)
                forecast_chart = Visualizer.plot_to_base64(fig)
                print("Prophet预测和图表生成成功")
            except Exception as e:
                print(f"Prophet预测失败: {str(e)}")
                import traceback
                traceback.print_exc()
                return jsonify({
                    'success': False,
                    'message': f'Prophet预测失败: {str(e)}'
                })
        
        # 绘制预测对比图
        try:
            # 只取最近30天的实际数据进行对比
            recent_data = ts_data.tail(30)
            comparison_title = f"{title_prefix}销售预测对比"
            fig = Visualizer.forecast_comparison(recent_data, forecast, title=comparison_title)
            comparison_chart = Visualizer.plot_to_base64(fig)
            print("预测对比图生成成功")
        except Exception as e:
            print(f"绘制预测对比图失败: {str(e)}")
            import traceback
            traceback.print_exc()
            comparison_chart = None
        
        # 返回预测结果和图表
        response_data = {
            'forecast': [
                {'date': date.strftime('%Y-%m-%d'), 'value': float(value)} 
                for date, value in zip(forecast.index, forecast['sales_quantity_pred'])
            ],
            'actual': [
                {'date': date.strftime('%Y-%m-%d'), 'value': float(value)} 
                for date, value in zip(recent_data.index, recent_data['sales_quantity'])
            ],
            'charts': {
                'forecast': forecast_chart if model_type == 'prophet' else None,
                'comparison': comparison_chart
            }
        }
        
        # 如果有盲盒ID，添加盲盒信息
        if box_id and 'name' in df.columns and not df.empty:
            response_data['box_info'] = {
                'id': box_id,
                'name': df.iloc[0]['name'] if 'name' in df.columns else '',
                'category': df.iloc[0]['category'] if 'category' in df.columns else ''
            }
        
        return jsonify({
            'success': True,
            'data': response_data
        })
    except Exception as e:
        print(f"销售预测API整体异常: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'预测分析过程中发生错误: {str(e)}'
        })

@analytics.route('/api/seasonality_analysis')
@login_required
def api_seasonality_analysis():
    """季节性分析API"""
    try:
        # 获取请求参数
        category = request.args.get('category')
        days = int(request.args.get('days', 365))
        period = request.args.get('period', 'weekly')  # 'weekly', 'monthly'
        
        print(f"季节性分析请求参数: category={category}, days={days}, period={period}")
        
        # 月度分析至少需要730天(2年)的数据
        if period == 'monthly' and days < 730:
            print(f"月度季节性分析通常需要至少2年数据，当前天数: {days}")
            days = max(days, 730)  # 自动增加到至少2年
            print(f"已调整为: {days}天")
        
        # 加载数据
        loader = DataLoader()
        df = loader.get_sales_data(days=days, category=category)
        
        print(f"加载的数据点数量: {len(df)}")
        
        # 数据不足
        if len(df) < 30:
            print("历史数据不足，无法进行季节性分析")
            return jsonify({
                'success': False,
                'message': '历史数据不足，无法进行季节性分析'
            })
        
        # 针对月度分析的额外数据验证
        if period == 'monthly':
            # 检查数据是否跨足够多个月
            unique_months = pd.to_datetime(df['date']).dt.to_period('M').nunique()
            if unique_months < 12:
                print(f"数据仅包含{unique_months}个月，不足以进行月度季节性分析")
                return jsonify({
                    'success': False,
                    'message': f'数据仅包含{unique_months}个月，月度季节性分析至少需要12个月数据'
                })
        
        # 按类别聚合
        if category:
            # 已经按类别筛选，直接按日期聚合
            agg_df = df.groupby('date')['sales_quantity'].sum().reset_index()
            agg_df = pd.DataFrame({
                'date': agg_df['date'],
                'sales_quantity': agg_df['sales_quantity']
            })
        else:
            # 所有类别，按日期聚合
            agg_df = df.groupby('date')['sales_quantity'].sum().reset_index()
            agg_df = pd.DataFrame({
                'date': agg_df['date'],
                'sales_quantity': agg_df['sales_quantity']
            })
        
        print(f"聚合后的数据点数量: {len(agg_df)}")
        
        # 准备时间序列数据
        ts_data = loader.prepare_time_series_data(agg_df)
        
        # 创建季节性分析器
        analyzer = SeasonalityAnalyzer(ts_data)
        
        # 根据周期类型分析季节性
        if period == 'weekly':
            # 获取星期几模式
            pattern = analyzer.get_day_of_week_pattern()
            period_name = '星期'
        elif period == 'monthly':
            # 获取月度模式
            pattern = analyzer.get_monthly_pattern()
            period_name = '月份'
        else:
            # 尝试进行分解，默认7天周期
            try:
                decomposition = analyzer.analyze_seasonality(period=7)
                pattern = decomposition.seasonal
                period_name = '周期'
                
                # 生成季节性分解图
                fig = analyzer.plot_seasonality()
                seasonality_chart = Visualizer.plot_to_base64(fig)
            except Exception as e:
                print(f"季节性分解失败: {str(e)}")
                import traceback
                traceback.print_exc()
                return jsonify({
                    'success': False,
                    'message': f'季节性分解失败: {str(e)}'
                })
        
        # 绘制季节性模式图
        fig = Visualizer.seasonality_analysis(pattern, title=f'{period_name}销售模式')
        pattern_chart = Visualizer.plot_to_base64(fig)
        print("季节性模式图生成成功")
        
        # 返回分析结果
        return jsonify({
            'success': True,
            'data': {
                'pattern': [
                    {period_name: idx, 'value': float(val)} 
                    for idx, val in zip(pattern.index, pattern.values)
                ],
                'charts': {
                    'pattern': pattern_chart,
                    'decomposition': seasonality_chart if period not in ['weekly', 'monthly'] else None
                }
            }
        })
    except Exception as e:
        print(f"季节性分析API整体异常: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'季节性分析过程中发生错误: {str(e)}'
        })

@analytics.route('/api/price_elasticity')
@login_required
def api_price_elasticity():
    """价格弹性分析API"""
    try:
        # 获取请求参数
        days = int(request.args.get('days', 365))
        by_category = request.args.get('by_category', 'true').lower() == 'true'
        
        print(f"价格弹性分析请求参数: days={days}, by_category={by_category}")
        
        # 加载数据
        loader = DataLoader()
        df = loader.get_sales_data(days=days)
        
        print(f"加载的数据点数量: {len(df)}")
        
        # 数据不足或缺少平均价格列
        if len(df) < 30 or 'avg_price' not in df.columns:
            print("历史数据不足或缺少价格信息，无法进行价格弹性分析")
            return jsonify({
                'success': False,
                'message': '历史数据不足或缺少价格信息，无法进行价格弹性分析'
            })
        
        # 创建价格弹性分析器
        analyzer = PriceElasticityAnalyzer(df)
        
        if by_category:
            # 确保数据包含类别信息
            if 'category' not in df.columns:
                print("数据缺少类别信息，无法按类别分析")
                return jsonify({
                    'success': False,
                    'message': '数据缺少类别信息，无法按类别分析'
                })
                
            # 按类别分析价格弹性
            elasticity_results = analyzer.analyze_by_category()
            
            # 如果没有得到任何结果
            if not elasticity_results:
                print("未能获取任何类别的价格弹性，可能数据量不足")
                return jsonify({
                    'success': False,
                    'message': '未能获取任何类别的价格弹性，可能数据量不足'
                })
            
            # 绘制类别价格弹性对比图
            fig = Visualizer.elasticity_by_category(elasticity_results)
            elasticity_chart = Visualizer.plot_to_base64(fig)
            print("类别价格弹性图生成成功")
            
            # 返回分析结果
            return jsonify({
                'success': True,
                'data': {
                    'elasticity': [
                        {'category': cat, 'elasticity': float(val)} 
                        for cat, val in elasticity_results.items()
                    ],
                    'charts': {
                        'elasticity': elasticity_chart
                    }
                }
            })
        else:
            # 分析整体价格弹性
            try:
                result = analyzer.calculate_elasticity()
                elasticity = result['elasticity']
                
                # 绘制价格-销量关系图
                fig = analyzer.plot_elasticity()
                elasticity_chart = Visualizer.plot_to_base64(fig)
                print("价格-销量关系图生成成功")
                
                # 弹性解释
                if abs(elasticity) > 1:
                    interpretation = "销量对价格变化非常敏感"
                elif abs(elasticity) < 0.5:
                    interpretation = "销量对价格变化不敏感"
                else:
                    interpretation = "销量对价格变化中度敏感"
                    
                # 返回分析结果
                return jsonify({
                    'success': True,
                    'data': {
                        'elasticity': float(elasticity),
                        'interpretation': interpretation,
                        'charts': {
                            'elasticity': elasticity_chart
                        }
                    }
                })
            except Exception as e:
                print(f"价格弹性分析失败: {str(e)}")
                import traceback
                traceback.print_exc()
                return jsonify({
                    'success': False,
                    'message': f'价格弹性分析失败: {str(e)}'
                })
    except Exception as e:
        print(f"价格弹性分析API整体异常: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'价格弹性分析过程中发生错误: {str(e)}'
        })

@analytics.route('/api/analytics/user_behavior')
@login_required
def get_user_behavior_data():
    days = int(request.args.get('days', 7))
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days-1)
    
    # 生成日期列表
    dates = []
    current_date = start_date
    while current_date <= end_date:
        dates.append(current_date.strftime('%Y-%m-%d'))
        current_date += timedelta(days=1)
    
    # 定义行为类型映射
    behavior_mapping = {
        'page_views': UserBehavior.TYPE_PAGE_VIEW,
        'product_views': UserBehavior.TYPE_VIEW_BOX,
        'market_views': UserBehavior.TYPE_VIEW_MARKET,
        'order_views': UserBehavior.TYPE_VIEW_ORDER,
        'cart_adds': UserBehavior.TYPE_ADD_CART,
        'form_submits': UserBehavior.TYPE_FORM_SUBMIT,
        'chats': UserBehavior.TYPE_CHAT
    }
    
    # 查询每种行为的数据
    behaviors = {key: [] for key in behavior_mapping.keys()}
    
    # 获取每天的行为数据
    for date in dates:
        day_start = datetime.strptime(date, '%Y-%m-%d')
        day_end = day_start + timedelta(days=1)
        
        # 查询每种行为的数量
        for behavior_key, action_type in behavior_mapping.items():
            count = db.session.query(UserBehavior).filter(
                UserBehavior.create_time >= day_start,
                UserBehavior.create_time < day_end,
                UserBehavior.action_type == action_type
            ).count()
            behaviors[behavior_key].append(count)
    
    return jsonify({
        'dates': dates,
        'cart_adds': behaviors['cart_adds'],
        'chats': behaviors['chats'],
        'form_submits': behaviors['form_submits'],
        'page_views': behaviors['page_views'],
        'product_views': behaviors['product_views'],
        'market_views': behaviors['market_views'],
        'order_views': behaviors['order_views']
    })
